package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.model.constant.DmcConstant;
import com.csun.cmny.provider.model.domain.DmcCsunButtonLocation;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.dto.button.BindCsunButtonLocationDto;
import com.csun.cmny.provider.model.dto.button.CsunButtonPageQuery;
import com.csun.cmny.provider.model.dto.device.DmcEditDeviceDto;
import com.csun.cmny.provider.model.enums.device.DmcDeviceTypeEnum;
import com.csun.cmny.provider.model.vo.OldmanBedRoomBuildingVo;
import com.csun.cmny.provider.model.vo.csunbutton.DmcCsunButtonVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcCsunButtonLocationService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.csun.cmny.provider.validator.DmcDeviceEditValidator;
import com.csun.cmny.util.PubUtils;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-08 13:20
 * @Description: the dmc device csun button controller
 */
@RestController
@RequestMapping(value = "/button", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcCsunButtonController extends BaseController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private DmcDeviceService dmcDeviceService;

    @Resource
    private DmcCsunButtonLocationService dmcCsunButtonLocationService;

    /**
     * 查询组织紧急按钮设备列表
     *
     * @param csunButtonPageQuery   the csun button page query
     *
     * @return  the wrapper
     */
    @ApiOperation(httpMethod = "POST", value = "查询组织紧急按钮设备列表")
    @RequestMapping(value = "/queryGroupCsunButtonListWithPage", method = RequestMethod.POST)
    public Wrapper queryGroupCsunButtonListWithPage(@RequestBody CsunButtonPageQuery csunButtonPageQuery) {

        csunButtonPageQuery.setGroupId(getLoginAuthDto().getGroupId());
        csunButtonPageQuery.setDeviceType(DmcDeviceTypeEnum.CSUN_BUTTON.getIndex());

        PageInfo pageInfo = dmcCsunButtonLocationService
                .queryGroupCsunButtonListWithPage(csunButtonPageQuery);
        for (Object o : pageInfo.getList()) {
            DmcCsunButtonVo dmcCsunButtonVo = (DmcCsunButtonVo) o;
            if (!PubUtils.isNull(dmcCsunButtonVo.getBindType())) {
                dmcCsunButtonVo.setBind(true);
                switch (dmcCsunButtonVo.getBindType()) {
                    case DmcConstant.CSUN_BUTTON_BIND_TYPE_OLDMAN :
                        OldmanBedRoomBuildingVo obv = (OldmanBedRoomBuildingVo) redisTemplate
                                .opsForValue().get(RedisKeyUtil.getOmcOldmanId(dmcCsunButtonVo.getOldmanId()));
                        replaceOldmanInfo(dmcCsunButtonVo, obv);
                        break;
                    case DmcConstant.CSUN_BUTTON_BIND_TYPE_BED :
                        OldmanBedRoomBuildingVo bov = (OldmanBedRoomBuildingVo) redisTemplate
                                .opsForValue().get(RedisKeyUtil.getOmcBedId(dmcCsunButtonVo.getBedId()));
                        replaceOldmanInfo(dmcCsunButtonVo, bov);
                        break;
                }
            }
        }

       // return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * replace oldman info
     *
     * @param dmcCsunButtonVo   the dmc csun button vo
     * @param obv   the oldman bed room building vo
     */
    public void replaceOldmanInfo(DmcCsunButtonVo dmcCsunButtonVo, OldmanBedRoomBuildingVo obv) {

        if (PublicUtil.isNotEmpty(obv)) {
            // 绑定床位, 老人信息和位置根据老人Id获取
            dmcCsunButtonVo.setOldmanName(obv.getOldmanName());
            if (PublicUtil.isNotEmpty(obv.getLocation())) {
                /**
                 * @date    2019-05-06
                 * @auth    chisj
                 * @desc    解决老人出院，换床位置信息未更新bug #1837
                 */
                /**
                 * @date    2019-05-28
                 * @author  chisj
                 * @desc    显示【房间-床位】 #2812
                 */
                if (PublicUtil.isNotEmpty(obv.getRoomNo()) && PublicUtil.isNotEmpty(obv.getBedNo())) {
                    dmcCsunButtonVo.setLocation(obv.getRoomNo() + "-" + obv.getBedNo());
                } else {
                    dmcCsunButtonVo.setLocation("--");
                }
            }
        }
    }

    /**
     * 添加紧急按钮设备
     *
     * @param dmcEditDeviceDto  the dmc edit device dto
     * @param br                the binding result
     *
     * @return  the wrapper
     */
    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "添加紧急按钮设备")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Wrapper addCsunButton(@Validated @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();

        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.CSUN_BUTTON.getIndex());

        Integer result = dmcDeviceService.addDevice(dmcDevice, getLoginAuthDto());

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 修改紧急按钮设备
     *
     * @param dmcEditDeviceDto  the dmc edit device dto
     * @param br                the binding result
     *
     * @return  the wrapper
     */
    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "修改紧急按钮设备")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Wrapper editCsunButton(@Validated(value = {DmcDeviceEditValidator.class})
                                   @RequestBody DmcEditDeviceDto dmcEditDeviceDto, BindingResult br) {

        DmcDevice dmcDevice = new DmcDevice();
        BeanUtils.copyProperties(dmcEditDeviceDto, dmcDevice);
        dmcDevice.setDeviceType(DmcDeviceTypeEnum.CSUN_BUTTON.getIndex());

        Integer result = dmcDeviceService.editDevice(dmcDevice, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 删除redisKey
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 根据Id删除紧急按钮
     *
     * @param id    the id
     *
     * @return  the wrapper
     */
    @ApiOperation(httpMethod = "POST", value = "根据Id删除紧急按钮")
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.POST)
    public Wrapper deleteDmcCsunButtonById(@PathVariable Long id) {

        Integer result = dmcCsunButtonLocationService.deleteCsunButtonById(id);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 删除redisKey
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 绑定紧急按钮
     *
     * @param bindCsunButtonLocationDto bind csun button location dto
     *
     * @return the wrapper.
     */
    @ValidateAnnotation
    //@LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/bindCsunButtonLocation", method = RequestMethod.POST)
    public Wrapper bindCsunButtonLocation(@Validated @RequestBody BindCsunButtonLocationDto bindCsunButtonLocationDto,
                                     BindingResult br) {

        Integer result = dmcCsunButtonLocationService.bindCsunButtonLocation(bindCsunButtonLocationDto,
                getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 添加redisKey
        }

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 解绑紧急按钮
     *
     * @param deviceId  device id
     *
     * @return  the wrapper.
     */
   // @LogAnnotation(isSaveResponseData = true, isSaveRequestData = true)
    @RequestMapping(value = "/breakCsunButtonLocation/{deviceId}", method = RequestMethod.POST)
    public Wrapper breakCsunButtonLocation(@PathVariable Long deviceId) {

        Integer result = dmcCsunButtonLocationService.breakCsunButtonLocation(deviceId);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        } else {
            // 删除redisKey
        }

      //  return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 添加紧急按钮报警时间
     */
    @PostMapping("/editCsunButtonAlarmTime")
    public Wrapper editCsunButtonAlarmTime(@RequestBody DmcCsunButtonLocation dmcCsunButtonLocation){
        DmcCsunButtonLocation dmcCsunButton = new DmcCsunButtonLocation();
        dmcCsunButton.setDeviceId(dmcCsunButtonLocation.getDeviceId());
        dmcCsunButton.setAlarmTime(dmcCsunButtonLocation.getAlarmTime());
        Integer result = dmcCsunButtonLocationService.update(dmcCsunButton);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }
}
